package com.shelpe.services.sinbadgateway.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Setter
@Slf4j
public class AppTokenExtractFilter implements Filter{

	private String tokenName;
	private String appName;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (SecurityContextHolder.getContext().getAuthentication() == null && this.tokenName != null) {
			String tokenValue = request.getParameter(tokenName);
			log.debug("extract app token from php request {}: {}", this.tokenName, tokenValue);
			if(StringUtils.isNotBlank(tokenValue)){
				TestingAuthenticationToken token = new TestingAuthenticationToken(this.appName, tokenValue);
				SecurityContextHolder.getContext().setAuthentication(token);
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}

}
